<?php
namespace app\base\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Common extends Controller
{

    /**
     *删除商品属性
     * @return mixed
     */
    public function ajaxDelShopAttr()
    {
        $attr_id = $this->request->get('attr_id');//属性ID
        $goods_id = $this->request->get('goods_id');//商品ID
        //判断是否有库存属性
        $data = Db::table('shop_goods_num')->where('goods_id',$goods_id)->column('goods_attr_id');
        foreach($data as $v)
        {
            $v = explode(',',$v);

            if(in_array($attr_id,$v))
            {//有库存
                return json(['code'=>-1,'msg'=>'库存使用此属性，无法删除']);
            }
        }
        Db::table('shop_goods_attr')->where('id',$attr_id)->delete();
        return json(['code'=>0,'msg'=>'删除成功']);
    }

    /**
     *商品获取类型属性
     * @return \think\response\Json
     */
    public function ajaxGetTypeAttr()
    {
        $id = $this->request->get('type_id');
        $data = Db::table('shop_attribute')->where('type_id',$id)->select();
        return json($data);
    }

    /**
     * 商品删除图片
     * @return \think\response\Json
     */
    public function ajaxDelPic()
    {
        $id = $this->request->get('pid');
        Db::table('shop_goods_pic')->where('id',$id)->delete();
        return json(['msg'=>'ok']);
    }


    /**
     * 删除描述
     * @return \think\response\Json
     */
    public function ajaxDelShopDesc()
    {
        $id = $this->request->get('id');
        Db::table('shop_goods_desc')->where('id',$id)->update(['is_usable'=>0]);
        return json(['code'=>0,'msg'=>'ok']);
    }

    /**
     * 修改描述
     * @return \think\response\Json
     */
    public function ajaxEditShopDesc()
    {
        $id = $this->request->post('id');
        $desc_name = $this->request->post('desc_name');
        $params = Request::instance()->post(false);
        $content = $params['goods_desc'];
        $_goods_desc = Db::table('shop_goods_desc')->where('id',$id)->field('id,goods_id,sign,desc_name,desc_content')->find();
        if($_goods_desc['sign'] != md5($params['goods_desc'])) {//商品描述改变
            //将原来默认的删除
            Db::table('shop_goods_desc')->where(['id'=>$_goods_desc['id']])->update(['is_usable'=>0]);
            //现将商品描述插入
            $_res1 = Db::table('shop_goods_desc')->insertGetId([
                'goods_id'=>$_goods_desc['goods_id'],
                'desc_name'=>$desc_name,
                'desc_content'=>$params['goods_desc'],
                'sign'=>md5($params['goods_desc']),
                'created_at'=>time(),
            ]);
        } else {
            Db::table('shop_goods_desc')->where(['id'=>$_goods_desc['id']])->update(['desc_name'=>$desc_name]);
        }
        return json(['code'=>0,'msg'=>'保存成功']);
    }

}